package com.encyclopedia.controller;

import com.encyclopedia.config.Base64;
import com.encyclopedia.result.JsonRequest;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.FastByteArrayOutputStream;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author MaLiang
 * @version 1.0
 * @date 2024-04-26 14:03
 */
@RestController
@RequestMapping("/plan/login")
@Slf4j
public class CaptchaController {

    @Autowired
    @Qualifier("captchaProducer")
    private Producer captchaProducer;

    @Autowired
    @Qualifier("captchaProducerMath")
    private Producer captchaProducerMath;

    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("/captchaImage")
    public JsonRequest getCode() {
        String uuid = UUID.randomUUID().toString();
        String verifyKey = "captcha_codes:" + uuid;

        String capStr = null, code = null;
        BufferedImage image = null;

        String captchaType = "math";

        if ("math".equals(captchaType)) {
            String capText = captchaProducerMath.createText();
            capStr = capText.substring(0, capText.lastIndexOf("@"));
            code = capText.substring(capText.lastIndexOf("@") + 1);
            image = captchaProducerMath.createImage(capStr);
        }
        FastByteArrayOutputStream os = new FastByteArrayOutputStream();
        try {
            ImageIO.write(image, "jpg", os);
        } catch (IOException e) {
            return JsonRequest.error("验证码生成失败");
        }
        redisTemplate.opsForValue().set(verifyKey, code, 300);
        Map<String, Object> map = new HashMap<>();
        map.put("uuid", uuid);
        map.put("img", Base64.encode(os.toByteArray()));
        return JsonRequest.success(map);
    }

}
